package org.sgs.toolbox.sql;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSet;

public class GenericRecordList implements Iterator<Object>{
	
	private ResultSetWrappingSqlRowSet rowSet;
	private Map<String, Integer> columnNameToIndexMap;
	
	public GenericRecordList(ResultSetWrappingSqlRowSet rowSet){
		this.rowSet = rowSet;
		columnNameToIndexMap = new HashMap<String, Integer>();
		for(int i = 0; i < getColumnCount(); i++){
			columnNameToIndexMap.put(rowSet.getMetaData().getColumnName(i + 1), i);
		}
	}

	public GenericRecord next(){
		rowSet.next();
		Object[] row = new Object[getColumnCount()];
		for(int i = 0; i < getColumnCount(); i++){
			row[i] = rowSet.getObject(i + 1); // 1-based index
		}
		return new GenericRecord(row, columnNameToIndexMap);
	}

	public int getColumnCount(){
		return rowSet.getMetaData().getColumnCount();
	}
	
	public String getColumnName(int index){
		int tmpIndex = index + 1; // 1-based index
		return rowSet.getMetaData().getColumnName(tmpIndex);
	}
	
	public String asCsv(){
		
		rowSet.beforeFirst();
		
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < getColumnCount(); i++){
			sb.append(getColumnName(i));
			if( i < getColumnCount() - 1){
				sb.append(",");
			}
		}
		sb.append("\n");
		while(hasNext()){
			GenericRecord record = next();
			String recordString = record.toString(",");
			sb.append(recordString);
			if(hasNext()){
				sb.append("\n");
			}
		}
		return sb.toString();
	}
	
	@Override
	public boolean hasNext() {
		return !rowSet.isLast();
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

}
